/**************************************************************************************************
 * @file        os_memery.h
 * @brief       跨平台智能指针容器封装，基于std::unique_ptr和std::shared_ptr实现
 * @details     提供使用自定义内存分配器的智能指针容器，支持内存追踪和自动释放功能
 *
 * @author      taoist.luo
 * @version     1.0.0
 * @date        2024-09
 *
 * Copyright (c) 2024 taoist.luo (https://gitee.com/harmonyluo(https://blog.csdn.net/harmonyluo))
 *
 * MIT License
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *************************************************************************************************/

#pragma once

#include <cstdlib>

#include "memery/os_allocator.h"

template <typename T>
class os_deleter
{
public:
    void operator()(T* ptr) const
    {
        os_delete ptr;
    }
};

template <typename T>
using os_unique_ptr = std::unique_ptr<T, os_deleter<T>>;

template <typename T>
using os_shared_ptr = std::shared_ptr<T>;

template <typename T>
using os_weak_ptr = std::weak_ptr<T>;

template <typename T, typename... Args>
os_unique_ptr<T> os_make_unique_impl(const char* file, int line, Args&&... args)
{
    T* ptr = os_new_super(T, std::forward<Args>(args)...);
    return os_unique_ptr<T>(ptr);
}

template <typename T, typename... Args>
os_shared_ptr<T> os_make_shared_impl(const char* file, int line, Args&&... args)
{
    // 注意：这里不能直接使用std::make_shared，因为它会绕过我们的内存跟踪机制
    // 但我们可以使用std::allocate_shared配合自定义allocator来实现相同效果
    // 这样既保持了性能优势(一次分配)，又能追踪内存
    return std::allocate_shared<T>(os_allocator<T>(file, line), std::forward<Args>(args)...);
}
// 定义宏来自动传递文件名和行号
#define os_make_unique(T, ...) os_make_unique_impl<T>(__FILE__, __LINE__, ##__VA_ARGS__)
#define os_make_shared(T, ...) os_make_shared_impl<T>(__FILE__, __LINE__, ##__VA_ARGS__)
